package com.peppa.petshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peppa.petshop.entity.Cart;
import com.peppa.petshop.entity.Good;
import com.peppa.petshop.mapper.CartMapper;
import com.peppa.petshop.mapper.GoodMapper;
import com.peppa.petshop.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peppa.petshop.vo.CartVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张三
 * @since 2021-06-02
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired(required = false)
    private CartMapper cartMapper;
    @Autowired(required = false)
    private GoodMapper goodMapper;
    @Override
    public String add(Integer goodId, Integer customerId) {
        Integer id = null;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("good",goodId);
        queryWrapper.eq("customer",customerId);
        Cart one = cartMapper.selectOne(queryWrapper);
        if (one !=null){
            return "宝贝已经在您的购物车里了，快去把它带回家吧";
        }
        Good good = goodMapper.selectById(goodId);
        if (good.getCount()>0){
            Cart cart = new Cart(id,customerId,goodId, LocalDateTime.now(),1);
            int i = cartMapper.insert(cart);
            if (i!=-1){
                return "加购成功";
            }
        }
        return "小宝贝已经被人捷足先登了哦，下次请早";
    }

    @Override
    public List<CartVO> cartList(Integer customerId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("customer",customerId);
        List<Cart> list = cartMapper.selectList(queryWrapper);
        ArrayList<CartVO> cartVOS = new ArrayList<>();
        for (Cart cart : list) {
            CartVO cartVO = new CartVO();
            BeanUtils.copyProperties(cart,cartVO);
            Integer goodId = cart.getGood();
            Good good = goodMapper.selectById(goodId);
            String goodName = good.getGoodName();
            cartVO.setGoodId(goodId);
            cartVO.setGood(goodName);
            cartVO.setPrice(good.getPrice());
            cartVOS.add(cartVO);
        }
        return cartVOS;
    }


}
